/*
 * @Author: yangzonglong
 * @Date: 2021-05-25 15:12:16
 * @version: v1.0.0
 * @Descripttion: table 控制器
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-29 16:19:36
 * @Auditor:
 */
import React, { useCallback, useMemo, useState } from 'react';
import { Form, Input, Checkbox, Radio, InputNumber, Modal } from 'antd';
import update from 'immutability-helper';
import Columns from './columns/Columns';
import ModalForm from './_ModalForm';
import CodeMirror from '@uiw/react-codemirror';
import ButtonGroup from './buttonGroup/ButtonGroup';
import { javascript } from '@codemirror/lang-javascript';
import Icon from './../icon/Icon';
import DashedBtn from './columns/_dashButton';
import ShowPrintController from '../components/ShowPrintController';
import useControlOptions from '../../hooks/useControlOptions';
import { CompoentTableProps } from './Table';
import { ColumnType, ControllerMap } from './config';
import CommonCodeMirror from './../../components/codeMirror/CodeMirror';

const FormItem = Form.Item;
const width = { width: '100%' };
const extensions = [javascript({ jsx: true })];
const screenIcon: React.CSSProperties = {
  position: 'absolute',
  right: 0,
  top: '20px'
};


export default () => {
  const [curColumn, _setCurColumn] = useState<ColumnType>({} as any);
  const [visible, setVisible] = useState(false);
  const [visibleModal, setVisibleModal] = useState(false);
  const [codeMirrorValue, setCodeMirrorValue] = useState('');

  const { options, changeControlProps, changeTableCurrent } = useControlOptions<CompoentTableProps>('tableProps');

  const showItemNo = options.tableProps.showItemNo as any;

  function show() {
    setVisibleModal(true);
    setCodeMirrorValue(options?.scriptText || '');
  }

  function onOk() {
    setVisibleModal(false);

    changeControlProps(
      'scriptText',
      codeMirrorValue,
      true
    );

    setCodeMirrorValue('');
  }


  const setCurColumn = useCallback(
    (curColumn: ColumnType) => {
      _setCurColumn(curColumn);
      changeTableCurrent(curColumn, setCurColumn);
    },
    [changeTableCurrent]
  );

  const changeTitle = useCallback(
    (e) => {
      changeControlProps('title', e.target.value, true);
    },
    [changeControlProps]
  );

  const changeTitleEn = useCallback(
    (e) => {
      changeControlProps('titleEn', e.target.value, true);
    },
    [changeControlProps]
  );

  // 同步table columns
  const changeColumnOptions = useCallback(
    (k: string, v: any, originalIndex?: number) => {
      const columns = options.tableProps.columns;
      const index = columns.findIndex((item) => item.key === curColumn.key);
      const newColumn = update(columns[index], {
        options: { $merge: !!k ? { [k]: v } : { ...v } },
        originalIndex: { $set: originalIndex },
      });

      setCurColumn(newColumn);

      changeControlProps(
        'tableProps',
        update(options.tableProps, {
          showItemNo: {
            $set: showItemNo,
          },
          columns: { $splice: [[index, 1, newColumn]] },
        }),
        true
      );
    },
    [options.tableProps, setCurColumn, changeControlProps, showItemNo, curColumn.key]
  );


  const Controller = ControllerMap[curColumn.type];

  const _options = useMemo(() => {
    return {
      ...curColumn,
      ...curColumn.options,
      keyValue: curColumn.key
    };
  }, [curColumn]);

  return (
    <>
      <ModalForm
        visible={visible}
        onOK={(res: any) => {
          setVisible(false);
          changeControlProps(
            'tableProps',
            update(options.tableProps, {
              initialValue: {
                $set: res,
              },
            }),
            true);
        }}
        onCancel={() => setVisible(false)}
        sendData={{}}
        scriptsChangeData={{}}
        formItemProps={options.formItemProps}
        tableProps={options.tableProps}
      />
      {curColumn.type ? (
        Controller && (
          <Controller
            changeControlProps={changeControlProps}
            changeColumnOptions={changeColumnOptions}
            setCurColumn={setCurColumn}
            {..._options}
            tableProps={options.tableProps}
            columns={options.tableProps.columns}
            showItemNo={options.tableProps.showItemNo}
            itemNoWidth={options.tableProps.itemNoWidth}
            bacthUploadData={options.tableProps.bacthUploadData}
          />
        )
      ) : (
        <>
          <FormItem label="数据绑定ID" tooltip="数据存储的名称/英文/必填">
            <Input value={options?.name} onChange={(e) => {
              changeControlProps('name', e.target.value, true);
            }} />
          </FormItem>

          <Form.Item label="标题">
            <Input onChange={changeTitle} value={options.title} />
          </Form.Item>

          <Form.Item label="英文标题">
            <Input onChange={changeTitleEn} value={options.titleEn} />
          </Form.Item>

          <FormItem className="antd-form-item-row" label="设置为大标题">
            <Checkbox
              checked={options.tableProps.showBigTitle}
              onChange={(e) => {
                changeControlProps(
                  'tableProps',
                  update(options.tableProps, {
                    showBigTitle: {
                      $set: e.target.checked,
                    },
                  }),
                  true
                );
              }}
            />
          </FormItem>

          <FormItem className="antd-form-item-row" label="列标题加粗">
            <Checkbox
              checked={options.tableProps.bigTitle}
              onChange={(e) => {
                changeControlProps(
                  'tableProps',
                  update(options.tableProps, {
                    bigTitle: {
                      $set: e.target.checked,
                    },
                  }),
                  true
                );
              }}
            />
          </FormItem>

          <ButtonGroup
            tabSource={undefined}
            dataSource={options.tableProps.btnGroup || []}
            changeControlProps={(value) => {
              changeControlProps(
                'tableProps',
                update(options.tableProps, {
                  btnGroup: {
                    $set: value,
                  },
                }),
                true
              );
            }} />

          <Columns setCurColumn={setCurColumn} options={options.tableProps} changeControlProps={changeControlProps} />

          <FormItem className="antd-form-item-row" label="显示行号">
            <Checkbox
              checked={options.tableProps.showItemNo}
              onChange={(e) => {
                changeControlProps(
                  'tableProps',
                  update(options.tableProps, {
                    showItemNo: {
                      $set: e.target.checked,
                    },
                  }),
                  true
                );
              }}
            />
          </FormItem>

          <FormItem className="antd-form-item-row" label="批量上传数据">
            <Checkbox
              checked={options.tableProps.bacthUploadData}
              onChange={(e) => {
                changeControlProps(
                  'tableProps',
                  update(options.tableProps, {
                    bacthUploadData: {
                      $set: e.target.checked,
                    },
                  }),
                  true
                );
              }}
            />
          </FormItem>

          {
            options.tableProps.bacthUploadData && (
              <>
                <CommonCodeMirror
                  label='导出模板脚本'
                  scriptText={options?.exportScriptText}
                  change={(e: string) => {
                    changeControlProps(
                      'exportScriptText',
                      e,
                      true
                    );
                  }} />

                <CommonCodeMirror
                  label='导入数据脚本'
                  scriptText={options?.scriptText}
                  change={(e: string) => {
                    changeControlProps(
                      'scriptText',
                      e,
                      true
                    );
                  }} />
              </>
            )
          }

          {options.tableProps.showItemNo && options?.print !== false && <FormItem label="打印行号宽度">
            <Radio.Group value={options.tableProps.itemNoWidth} onChange={(e) => changeControlProps(
              'tableProps',
              update(options.tableProps, {
                itemNoWidth: {
                  $set: e.target.value,
                },
              }),
              true
            )}>
              <Radio.Button value={106}>微</Radio.Button>
              <Radio.Button value={136}>小</Radio.Button>
              <Radio.Button value={200}>中</Radio.Button>
              <Radio.Button value={376}>大</Radio.Button>
            </Radio.Group>
          </FormItem>}

          <FormItem className="antd-form-item-row" label="是否必填">
            <Checkbox
              checked={options.required}
              onChange={(e) => {
                changeControlProps(
                  'required',
                  e.target.checked,
                  true
                );
              }}
            />
          </FormItem>

          <Form.Item label="默认值">
            <DashedBtn onClick={() => setVisible(true)} />
          </Form.Item>

          <Form.Item label='Y轴高度'>
            <InputNumber
              style={width}
              value={options.scrollY}
              onChange={(e) => {
                changeControlProps(
                  'scrollY',
                  e,
                  true
                );
              }}
            />
          </Form.Item>

          <FormItem className="antd-form-item-row" label="隐藏新增">
            <Checkbox
              checked={options.hideAdd}
              onChange={(e) => {
                changeControlProps(
                  'hideAdd',
                  e.target.checked,
                  true
                );
              }}
            />
          </FormItem>

          <FormItem className="antd-form-item-row" label="隐藏删除">
            <Checkbox
              checked={options.hideDelete}
              onChange={(e) => {
                changeControlProps(
                  'hideDelete',
                  e.target.checked,
                  true
                );
              }}
            />
          </FormItem>

          <ShowPrintController onChange={(key, value) => changeControlProps(key, value, true)} print={options?.print} />

          <FormItem className='antd-form-item-row' label='打印边框'>
            <Checkbox
              onChange={e => {
                changeControlProps('printBorder', e.target.checked, true);
              }}
              checked={options?.printBorder} />
          </FormItem>
        </>
      )}
    </>
  );
};
